package mobileModule

import (
	"errors"
	"fmt"
	"main/tools"
	"strconv"
	"strings"
)

// EC800N检查SIM卡
func EC800NCheckSIM(m *MobileModuleTemplate) {

	err, _ := m.MobileModuleWriteATCommand("AT+CPIN?\r\n", "READY", 2000)
	if err != nil {
		m.RunParam.SIMInsert = false
		fmt.Printf("移动模块SIM卡未检测到\n")
		return
	}
	m.RunParam.SIMInsert = true
	fmt.Printf("移动模块SIM卡检测到\n")
}

// 获取IC卡ID
func EC800NGetICCID(m *MobileModuleTemplate) {
	err, rxStr := m.MobileModuleWriteATCommand("AT+QCCID\r\n", "+QCCID:", 2000)
	if err != nil {
		m.RunParam.ICCID = ""
		fmt.Printf("移动模块ICCID未获取到\n")
		return
	}

	rxStrSlice := strings.Split(rxStr, "\r\n")
	for _, v := range rxStrSlice {
		if strings.Contains(v, "+QCCID: ") == true {
			index := strings.Index(v, "+QCCID: ") + 8
			m.RunParam.ICCID = v[index : index+19]
			fmt.Printf("移动模块ICCID[%v]\n", m.RunParam.ICCID)
			break
		}
	}
}

// 读取电话号
func EC800NGetIMEI(m *MobileModuleTemplate) {
	err, rxStr := m.MobileModuleWriteATCommand("AT+GSN\r\n", "OK", 1000)
	if err != nil {
		return
	}
	rxStrSlice := strings.Split(rxStr, "\r\n")
	for _, v := range rxStrSlice {
		if len(v) > 10 {
			m.RunParam.IMEI = v
			fmt.Printf("移动模块IMEI[%v]\n", m.RunParam.IMEI)
		}
	}
}

// 读取信号强度
func EC800NGetCSQ(m *MobileModuleTemplate) error {
	if m == nil {
		return errors.New("MobileModuleTemplate is nil")
	}
	err, rxStr := m.MobileModuleWriteATCommand("AT+CSQ\r\n", "OK", 1000)
	if err != nil {
		return errors.New("MobileModuleWriteATCommand error")
	}
	rxStrSlice := strings.Split(rxStr, "\r\n")
	for _, v := range rxStrSlice {
		if strings.Contains(v, "+CSQ:") == true {
			index1 := strings.Index(rxStrSlice[1], "CSQ: ") + 5
			index2 := strings.Index(rxStrSlice[1], ",")
			if index1 == -1 || index2 == -1 {
				fmt.Printf("移动模块信号强度接收失败\n")
				continue
			}
			m.RunParam.CSQ = rxStrSlice[1][index1:index2]

			csq, _ := strconv.Atoi(m.RunParam.CSQ)
			fmt.Printf("移动模块信号强度[%v]\n", csq)
			if csq < 10 {
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedHigh.GPIO, m.GPIOParam.RSSILedHigh.ResetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedMiddle.GPIO, m.GPIOParam.RSSILedMiddle.ResetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedLow.GPIO, m.GPIOParam.RSSILedLow.SetValue)
				fmt.Printf("移动模块信号强度弱\n")
			} else if csq >= 10 && csq < 25 {
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedHigh.GPIO, m.GPIOParam.RSSILedHigh.ResetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedMiddle.GPIO, m.GPIOParam.RSSILedMiddle.SetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedLow.GPIO, m.GPIOParam.RSSILedLow.SetValue)
				fmt.Printf("移动模块信号强度中\n")
			} else {
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedHigh.GPIO, m.GPIOParam.RSSILedHigh.SetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedMiddle.GPIO, m.GPIOParam.RSSILedMiddle.SetValue)
				tools.GPIOWriteCmd(m.GPIOParam.RSSILedLow.GPIO, m.GPIOParam.RSSILedLow.SetValue)
				fmt.Printf("移动模块信号强度强\n")
			}
		}
	}
	return nil
}

// 获取网络状态
func EC800NGetLocation(m *MobileModuleTemplate, cmd int) {

	setupFlag := false

	err, _ := m.MobileModuleWriteATCommand("AT+CREG=2\r\n", "OK", 1000)
	if err != nil {
		return
	}

	err, rxStr := m.MobileModuleWriteATCommand("AT+CREG?\r\n", "OK", 1000)
	if err != nil {
		return
	}

	rxStrSlice := strings.Split(rxStr, "\r\n")
	for _, v := range rxStrSlice {
		if strings.Contains(v, "+CREG") == true {
			tmpSlice := strings.Split(v, ",")
			if len(tmpSlice) == 5 {
				//判断网络注册状态
				if tmpSlice[1] == "1" || tmpSlice[1] == "5" {
					//从未注册变成注册
					if m.RunParam.Network == false {
						setupFlag = true
					}
					m.RunParam.Network = true
					fmt.Printf("移动模块网络状态[已注册]\n")
				} else {
					m.RunParam.Network = false
					fmt.Printf("移动模块网络状态[未注册]\n")
				}
				m.RunParam.Lac = strings.ReplaceAll(tmpSlice[2], "\"", "")
				m.RunParam.Ci = strings.ReplaceAll(tmpSlice[3], "\"", "")
			}
		}
	}

	//重新拨号
	if setupFlag == true || cmd == 1 {
		m.MobileModuleGetOperator()
		m.MobileModuleSetupDataCall()
	}
}

/*
获取运营商信息
*/
func EC800NGetOperator(m *MobileModuleTemplate) {
	err, rxStr := m.MobileModuleWriteATCommand("AT+COPS?\r\n", "+COPS:", 1000)
	if err != nil {
		return
	}

	rxStrSlice := strings.Split(rxStr, "\r\n")
	for _, v := range rxStrSlice {
		if strings.Contains(v, "+COPS:") == true {
			tmpSlice := strings.Split(v, ",")
			if len(tmpSlice) == 4 {
				fmt.Printf("Operator %v", tmpSlice[2])
				//判断网络注册状态
				if strings.Contains(tmpSlice[2], "CHN-UNICOM") { //移动、联通
					m.RunParam.Operator = OperatorTypeCMCCCUCC
					fmt.Printf("移动模块运营商[移动]\n")
				} else if strings.Contains(tmpSlice[2], "CHN-CT") { //电信
					m.RunParam.Operator = OperatorTypeCTCC
					fmt.Printf("移动模块运营商[电信]\n")
				} else {

				}
			}
		}
	}
}

// 拨号上网
func EC800NSetupDataCall(m *MobileModuleTemplate) {

	fmt.Printf("物联网卡运营商 %v\n", m.RunParam.Operator)
	err, _ := m.MobileModuleWriteATCommand("AT+QNETDEVCTL=1,1,1\r\n", "OK", 5000)
	if err != nil {
		fmt.Printf("移动网络发送AT拨号指令失败 %v\n", err.Error())
		return
	}
	//阻塞,动态获取有可能不成功
	err, errString, outString := tools.RunShellCmd("udhcpc", "-fnq", "-i", "usb0")
	if err != nil {
		fmt.Printf("移动网络拨号失败 %v %s\n", err.Error(), errString)
	} else {
		fmt.Printf("移动网络拨号成功 %v\n", outString)
	}

	/*
		//阻塞
		err, errString, outString = tools.RunShellCmd("/sbin/route", "del", "default", "gw", "192.168.43.1", "dev", "usb0")
		if err != nil {
			fmt.Printf("删除默认网关 %v %s", err.Error(), errString)
		} else {
			fmt.Printf("删除默认网关 %v", outString)
		}

		//阻塞
		err, errString, outString = tools.RunShellCmd("/sbin/route", "add", "-host", m.KeepAliveParam.IPMaster, "gw", "192.168.43.1", "dev", "usb0")
		if err != nil {
			fmt.Printf("添加手动路由 %v %s", err.Error(), errString)
		} else {
			fmt.Printf("添加手动路由 %v", outString)
		}
	*/
}
